<!--用户管理-->
<template>
  <div id="userManagePage">
    <!-- 搜索表单 -->
    <a-form layout="inline" :model="searchParams" @finish="doSearch">
      <a-form-item label="账号">
        <a-input v-model:value="searchParams.userAccount" placeholder="输入账号" allow-clear />
      </a-form-item>
      <a-form-item label="用户名">
        <a-input v-model:value="searchParams.userName" placeholder="输入用户名" allow-clear />
      </a-form-item>
      <a-form-item>
        <a-button type="primary" html-type="submit">搜索</a-button>
      </a-form-item>
    </a-form>
    <div style="margin-bottom: 16px" />
    <!-- 表格 -->
    <a-table
      :columns="columns"
      :data-source="dataList"
      :pagination="pagination"
      @change="doTableChange"
      bordered
      size="middle"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.dataIndex === 'userAvatar'">
          <a-image :src="record.userAvatar" :width="120" />
        </template>
        <template v-else-if="column.dataIndex === 'userRole'">
          <a-tag :color="record.userRole === 'admin' ? 'green' : 'blue'">
            {{ record.userRole === 'admin' ? '管理员' : '普通用户' }}
          </a-tag>
        </template>
        <template v-if="column.dataIndex === 'createTime'">
          {{ dayjs(record.createTime).format('YYYY-MM-DD HH:mm:ss') }}
        </template>
        <template v-else-if="column.key === 'action' && record.userRole !== 'admin'">
          <a-button
            danger
            style="margin-right: 10px"
            @click="showDeleteConfirm(record.id, record.userRole)"
            >删除
          </a-button>
          <a-button type="primary" @click="showUpdateConfirm(record)">修改</a-button>
          <a-button style="margin-left: 10px" @click="showResetPasswordConfirm(record.id)"
            >重置密码
          </a-button>
        </template>
      </template>
    </a-table>

    <!-- 确认删除对话框 -->
    <a-modal
      v-model:visible="confirmModalVisible"
      title="确认删除"
      @ok="handleDeleteOk"
      @cancel="handleDeleteCancel"
    >
      <p>您确定要删除该用户吗？</p>
    </a-modal>

    <a-modal
      v-model:visible="updateModalVisible"
      title="确认修改"
      @ok="handleDeleteOk"
      @cancel="handleDeleteCancel"
    >
      <a-form :model="formState" name="basic" autocomplete="off">
        <a-form-item
          label="昵称"
          name="userName"
          :rules="[{ required: true, message: '请输入昵称' }]"
        >
          <a-input v-model:value="formState.userName" placeholder="请输入昵称" allow-clear />
        </a-form-item>

        <a-form-item
          label="角色"
          name="userRole"
          :rules="[{ required: true, message: '请选择角色' }]"
        >
          <a-input-group compact>
            <a-select v-model:value="formState.userRole" style="width: 100%">
              <a-select-option value="user">普通用户</a-select-option>
              <a-select-option value="admin">管理员</a-select-option>
            </a-select>
          </a-input-group>
        </a-form-item>

        <a-form-item label="简介" name="userProfile" style="margin-left: 10px">
          <a-textarea v-model:value="formState.userProfile" />
        </a-form-item>
      </a-form>
    </a-modal>

    <!--重置密码对话框-->
    <a-modal
      v-model:visible="resetPasswordVisible"
      title="重置密码"
      @ok="handleResetPassword"
      @cancel="handleResetPasswordCancel"
    >
      <p>您确定要重置该用户密码吗？</p>
    </a-modal>
  </div>
</template>

<script lang="ts" setup>
import { computed, onMounted, reactive, ref } from 'vue'
import { message } from 'ant-design-vue'
import {
  deleteUserUsingPost,
  listUserVoByPageUsingPost,
  resetUserPasswordUsingGet,
} from '@/api/userController.ts'
import dayjs from 'dayjs'

// 新增的确认删除对话框显示控制变量
const confirmModalVisible = ref(false)
const resetPasswordVisible = ref(false)
const updateModalVisible = ref(false)
// noinspection TypeScriptValidateTypes
const deleteInfo = ref<{ id: number; userRole: string }>(null)

const userId = ref(0)

const columns = [
  {
    title: 'id',
    dataIndex: 'id',
    align: 'center',
    width: 280,
  },
  {
    title: '账号',
    dataIndex: 'userAccount',
    align: 'center',
  },
  {
    title: '昵称',
    dataIndex: 'userName',
    align: 'center',
  },
  {
    title: '头像',
    dataIndex: 'userAvatar',
    align: 'center',
  },
  {
    title: '简介',
    dataIndex: 'userProfile',
    align: 'center',
  },
  {
    title: '用户角色',
    dataIndex: 'userRole',
    align: 'center',
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    width: 180,
    align: 'center',
  },
  {
    title: '更新时间',
    dataIndex: 'updateTime',
    align: 'center',
  },
  {
    title: '操作',
    key: 'action',
    width: 300,
    align: 'center',
  },
]

const formState = reactive<API.UserUpdateRequest>({
  id: 0,
  userName: '',
  userRole: '',
  userAvatar: '',
  userProfile: '',
})

const showUpdateConfirm = (record: API.UserVO) => {
  formState.id = record.id
  formState.userName = record.userName
  formState.userRole = record.userRole
  formState.userAvatar = record.userAvatar
  formState.userProfile = record.userProfile
  updateModalVisible.value = true
}

const showDeleteConfirm = (id: number, userRole: string) => {
  deleteInfo.value = { id, userRole }
  confirmModalVisible.value = true
}

const handleDeleteOk = () => {
  if (deleteInfo.value) {
    doDelete(deleteInfo.value.id, deleteInfo.value.userRole)
  }
  confirmModalVisible.value = false
}

const handleDeleteCancel = () => {
  confirmModalVisible.value = false
  fetchData()
}

const showResetPasswordConfirm = (id: number) => {
  userId.value = id
  resetPasswordVisible.value = true
}

const handleResetPassword = () => {
  if (userId.value != 0) {
    resetUserPassword(userId.value)
  }
  resetPasswordVisible.value = false
}

const handleResetPasswordCancel = () => {
  resetPasswordVisible.value = false
}

const doDelete = async (id: number, userRole: string) => {
  if (userRole === 'admin') {
    message.error('无法删除管理账号')
  } else {
    const res = await deleteUserUsingPost({ id })
    if (res.data.code === 0) {
      message.success('删除成功')
      // 刷新数据
      await fetchData()
    } else {
      message.error('删除失败')
    }
  }
}

const resetUserPassword = async (id: number) => {
  const res = await resetUserPasswordUsingGet({ id })
  if (res.data.code === 0) {
    message.success('重置密码成功')
  } else {
    message.error('重置密码失败')
  }
}

// 数据
const dataList = ref<API.UserVO[]>([])
const total = ref(0)

// 搜索条件
const searchParams = reactive<API.UserQueryRequest>({
  current: 1,
  pageSize: 10,
  sortField: 'createTime',
  sortOrder: 'ascend',
})

// 获取数据
const fetchData = async () => {
  const res = await listUserVoByPageUsingPost({
    ...searchParams,
  })
  if (res.data.data) {
    dataList.value = res.data.data.records ?? []
    total.value = res.data.data.total ?? 0
  } else {
    message.error('获取数据失败，' + res.data.message)
  }
}

// 表格变化之后，重新获取数据
const doTableChange = (page: any) => {
  searchParams.current = page.current
  searchParams.pageSize = page.pageSize
  fetchData()
}

// 搜索数据
const doSearch = () => {
  // 重置页码
  searchParams.current = 1
  fetchData()
}

// 分页参数
const pagination = computed(() => {
  return {
    current: searchParams.current,
    pageSize: searchParams.pageSize,
    total: total.value,
    showSizeChanger: true,
    showTotal: (total) => `共 ${total} 条`,
  }
})

onMounted(() => {
  fetchData()
})
</script>

<style scoped>
@media (max-width: 768px) {
  .a-table tr:nth-child(even) {
    background-color: #f9f9f9;
  }

  .a-table tr:nth-child(odd) {
    background-color: #ffffff;
  }
}
</style>
